package com.esm.pdafx.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esm.pdafx.R;
import com.esm.pdafx.adapter.DemoAdapter;
import com.esm.pdafx.database.manager.SystemCenter;
import com.esm.pdafx.model.SBox;
import com.esm.pdafx.util.HttpRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.model.Entry;
import zuo.biao.library.util.JSON;

public class MainActivity extends BaseActivity implements View.OnClickListener, MyReceiver.Message {
    private static final String TAG = "MainActivity";

    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initEvent();

        myReceiver = new MyReceiver();
        myReceiver.message = this;
        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("com.android.server.scannerservice.broadcast");
//        intentFilter.addAction("com.android.server.scannerservice.broadcast2");
        intentFilter.addAction("android.intent.ACTION_DECODE_DATA");
        registerReceiver(myReceiver, intentFilter);

        tv_dqzkinfo.setText("");
        SystemCenter.getInstance().resetBarcode();
        updateData();

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time++;
                    if (time > 60) {
                        //最多间隔60秒获取信息
                        mHandler.sendEmptyMessage(FX_BASE);
                        time = 0;
                        break;
                    }
                }
            }
        }.start();
    }

    int time = 1000;
    public static final int FX_BASE = 1818;//封箱数
    public static final int BAOJING = 1819;//报警

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (FX_BASE == msg.what) {
                fengxiangbase();
            } else if (BAOJING == msg.what) {
                baojing();
            }
        }
    };

    void sendBroadcast() {
        //PDA无效, 联想pad 是ok的
        Intent intent = new Intent("com.android.server.scannerservice.broadcast2");
        intent.putExtra("scannerdata", "1231415");         //向广播接收器传递数据
        sendBroadcast(intent);
    }

    AssetFileDescriptor afd = null;
    AssetManager am = null;

    //错误扫码报警
    void baojing() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        //这里示例的代码是使用点击按钮的时候可以实现震动，在按钮的点击事件的函数中添加这样几句话
        /*这里使用的是一个长整型数组，数组的a[0]表示静止的时间，a[1]代表的是震动的时间，然后数组的a[2]表示静止的时间，
         * a[3]代表的是震动的时间……依次类推下去，然后这里的代码有一点小小的改变
         */
        long[] patter = {50, 1000};
        vibrator.vibrate(patter, -1);

        //播放声音
        if (am == null) {
            am = getAssets();
            try {
                afd = am.openFd("14184.mp3");
            } catch (IOException e) {

            }
        }
        initMediaPlayer();
    }

    private final MediaPlayer mediaPlayer = new MediaPlayer();
    private void initMediaPlayer() {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ListView lv_ncode;
    private TextView tv_dqzkinfo;
    private EditText edit_dqtm;
    private EditText edit_ddzxs;
    private EditText edit_yjhxs;
    private EditText edit_khdd;
    private EditText edit_dingdan;
    private EditText edit_wxtm;
    private EditText edit_style;
    private EditText edit_ysslzs;
    private TextView tv_jieguo;

    private TextView tv_sendBroadcast;

    @Override
    public void initView() {
        lv_ncode = (ListView) findViewById(R.id.lv_ncode);

        tv_dqzkinfo = (TextView) findViewById(R.id.tv_dqzkinfo);
        edit_dqtm = (EditText) findViewById(R.id.edit_dqtm);
        edit_ddzxs = (EditText) findViewById(R.id.edit_ddzxs);
        edit_yjhxs = (EditText) findViewById(R.id.edit_yjhxs);
        edit_khdd = (EditText) findViewById(R.id.edit_khdd);
        edit_dingdan = (EditText) findViewById(R.id.edit_dingdan);
        edit_wxtm = (EditText) findViewById(R.id.edit_wxtm);
        edit_style = (EditText) findViewById(R.id.edit_style);
        edit_ysslzs = (EditText) findViewById(R.id.edit_ysslzs);
        tv_sendBroadcast = (TextView) findViewById(R.id.tv_sendBroadcast);
        tv_sendBroadcast.setOnClickListener(this);

        tv_jieguo = (TextView) findViewById(R.id.tv_jieguo);

//        findViewById(R.id.tv_title).setOnClickListener(this);
        //禁止响应按键焦点
        lv_ncode.setFocusable(false);
    }

    private DemoAdapter adapter;

    private void setList(List<Entry<Integer, String>> list) {
        if (list == null) {
            return;
        }
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_ncode.setAdapter(adapter);
        }
        adapter.refresh(list);
    }

    private List<Entry<Integer, String>> demodataList;

    protected List<Entry<Integer, String>> getList() {
        demodataList = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < SystemCenter.getInstance().wbox.sboxList.size(); i++) {
            demodataList.add(new Entry<Integer, String>(i, ""));
        }
        return demodataList;
    }

    void updateData() {
        edit_ddzxs.setText(SystemCenter.getInstance().num + "");
        edit_yjhxs.setText(SystemCenter.getInstance().wnum + "");
        edit_khdd.setText(SystemCenter.getInstance().wbox.getKehu_po());
        edit_dingdan.setText(SystemCenter.getInstance().wbox.getPo());
        edit_wxtm.setText(SystemCenter.getInstance().wbox.getLpn());
        String style = "";
        if (SystemCenter.getInstance().wbox.sboxList.size() > 0) {
            style = SystemCenter.getInstance().wbox.sboxList.get(0).getStyle();
        }
        edit_style.setText(style);
        int wnum = 0;
        for (SBox sbox : SystemCenter.getInstance().wbox.sboxList) {
            wnum += sbox.getNum();
        }
        edit_ysslzs.setText(wnum + "/" + SystemCenter.getInstance().wbox.getShuangshu());

        setList(getList());

        if (SystemCenter.getInstance().lpn.isEmpty()) {
            tv_jieguo.setText(R.string.qswxm);
            tv_jieguo.setBackgroundColor(getResources().getColor(R.color.alpha_3));
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sendBroadcast:
                sendBroadcast();
                break;
            case R.id.tv_title:
                showVersion();
                break;
            default:
                break;
        }
    }

    void showVersion() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                showShortToast("版本号： V" + versionName);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d(TAG, "an error occured when collect package info" + e);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 514:
                //封箱按键
                SystemCenter.getInstance().isfx = 1;
                updatefxinfo();
                break;
            case 782:
                //扫码按键
                break;
            case KeyEvent.KEYCODE_POUND:
                //#键
                showVersion();
                break;

        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_9) {
            //弹出版本号
            showVersion();
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    void scanWcode(String lpn) {
        SystemCenter.getInstance().lpn = lpn;

        showProgressDialog(R.string.loading);
        try {
            HttpRequest.fengxianginfo(lpn, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    dismissProgressDialog();

                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    } else {
                        showShortToast(getString(R.string.wlwlj));
                        tv_dqzkinfo.setText(getString(R.string.wlwlj));
                        return;
                    }

                    if (code == 1) {
                        String data = jsonObject.getString("data");
                        JSONObject jsonObject2 = JSON.parseObject(data);
                        SystemCenter.getInstance().wbox.setId(1);
                        SystemCenter.getInstance().wbox.setLpn(jsonObject2.getString("lpn"));
                        SystemCenter.getInstance().wbox.setKehu_po(jsonObject2.getString("kehu_po"));
                        SystemCenter.getInstance().wbox.setPo(jsonObject2.getString("po"));
                        SystemCenter.getInstance().wbox.setKwh(jsonObject2.getString("kwh"));
                        SystemCenter.getInstance().wbox.setType(jsonObject2.getInteger("type"));
                        SystemCenter.getInstance().wbox.setShuangshu(jsonObject2.getInteger("shuangshu"));

                        JSONArray jsonArray2 = jsonObject2.getJSONArray("ncodelist");
                        for (int i = 0; i < jsonArray2.size(); i++) {
                            JSONObject a = jsonArray2.getJSONObject(i);
                            SBox sbox = new SBox();
                            sbox.setNcodeid(a.getString("ncodeid"));
                            sbox.setStyle(a.getString("style"));
                            sbox.setSize(a.getString("size"));
                            sbox.setNum(a.getInteger("num"));
                            sbox.setPlan_num(a.getInteger("plan_num"));
                            sbox.setNcode(a.getString("ncode"));
                            SystemCenter.getInstance().wbox.sboxList.add(sbox);
                        }

                        SystemCenter.getInstance().num = jsonObject2.getInteger("num");
                        SystemCenter.getInstance().wnum = jsonObject2.getInteger("wnum");

                        updateData();
                        tv_dqzkinfo.setText(R.string.zqdwxm);
                        time = 0;
                        tv_jieguo.setText("OK");
                        tv_jieguo.setBackgroundColor(getResources().getColor(R.color.green_deep));
                    } else {
                        mHandler.sendEmptyMessage(BAOJING);
                        SystemCenter.getInstance().resetBarcode();
                        tv_dqzkinfo.setText(R.string.cwdwxm);
                        tv_jieguo.setText("NO");
                        tv_jieguo.setBackgroundColor(getResources().getColor(R.color.red_interest));
                    }

                }
            });
        } catch (Exception e1) {
            showShortToast(getString(R.string.wlwlj));
            tv_dqzkinfo.setText(getString(R.string.wlwlj));
            dismissProgressDialog();
        }
    }

    void updatefxinfo() {
        String fxinfo_ncode = "";
        String fxinfo_num = "";
        for (SBox sbox : SystemCenter.getInstance().wbox.sboxList) {
            fxinfo_ncode += sbox.getNcode() + ",";
            fxinfo_num += sbox.getNum() + ",";
        }
        if (fxinfo_ncode.isEmpty()) {
            return;
        }
        fxinfo_ncode = fxinfo_ncode.substring(0, fxinfo_ncode.length() - 1);
        fxinfo_num = fxinfo_num.substring(0, fxinfo_num.length() - 1);
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.updatefxinfo(SystemCenter.getInstance().lpn, SystemCenter.getInstance().isfx, fxinfo_ncode, fxinfo_num, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    dismissProgressDialog();
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    } else {
                        showShortToast(getString(R.string.wlwlj));
                        tv_dqzkinfo.setText(getString(R.string.wlwlj));
                        return;
                    }

                    if (code == 1) {
                        showShortToast(getString(R.string.fxcg));
                        SystemCenter.getInstance().resetBarcode();
                        updateData();
                        tv_dqzkinfo.setText("");
                        edit_dqtm.setText("");
                    } else {
                        showShortToast(getString(R.string.wfx));
                        SystemCenter.getInstance().resetBarcode();
                        updateData();
                        tv_dqzkinfo.setText("");
                        edit_dqtm.setText("");
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast(getString(R.string.wlwlj));
            tv_dqzkinfo.setText(getString(R.string.wlwlj));
            dismissProgressDialog();
        }
    }

    void fengxiangbase() {
        try {
            HttpRequest.fengxiangbase(0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    } else {
                        showShortToast(getString(R.string.wlwlj));
                        tv_dqzkinfo.setText(getString(R.string.wlwlj));
                        return;
                    }

                    if (code == 1) {
                        String data = jsonObject.getString("data");
                        JSONObject jsonObject2 = JSON.parseObject(data);
                        SystemCenter.getInstance().num = jsonObject2.getInteger("num");
                        SystemCenter.getInstance().wnum = jsonObject2.getInteger("wnum");
                        updateData();
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast(getString(R.string.wlwlj));
            tv_dqzkinfo.setText(getString(R.string.wlwlj));
        }
    }

    @Override
    public void getMsg(String str) {
        //通过实现MyReceiver.Message接口可以在这里对MyReceiver中的数据进行处理
        showShortToast(str);
        edit_dqtm.setText(str);
        if (SystemCenter.getInstance().lpn.isEmpty()) {
            //扫外箱码
            //如果无外箱码，则为外箱码； 即外箱码必需先扫
            scanWcode(str);
        } else if (SystemCenter.getInstance().lpn.compareToIgnoreCase(str) == 0) {
            return;
        } else {
            //扫内盒
            boolean isFind = false;
            for (SBox sbox : SystemCenter.getInstance().wbox.sboxList) {
                if (str.compareToIgnoreCase(sbox.getNcode()) == 0) {
                    int num = sbox.getNum() + 1;
                    if (num > sbox.getPlan_num()) {
                        num = sbox.getPlan_num();
                        tv_dqzkinfo.setText(R.string.zqdnhmadd0);
                    } else {
                        tv_dqzkinfo.setText(R.string.zqdnhmadd1);
                    }
                    sbox.setNum(num);
                    isFind = true;
                }
            }
            if (isFind) {
                updateData();
                tv_jieguo.setText("OK");
                tv_jieguo.setBackgroundColor(getResources().getColor(R.color.green_deep));
            } else {
                mHandler.sendEmptyMessage(BAOJING);
                tv_dqzkinfo.setText(R.string.cwdnhm);
                tv_jieguo.setText("NO");
                tv_jieguo.setBackgroundColor(getResources().getColor(R.color.red_interest));
            }
        }

        //禁止响应按键焦点
        lv_ncode.setFocusable(false);

    }

}